#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    int countKConstraintSubstrings(string s, int k) {
        int left = 0, right = 0, max1 = 0, n = s.size();
        int one = 0, zero = 0;
        while (right < n)
        {
            while (right < n && (one <= k || zero <= k))
            {
                if (s[right] == '1') one++;
                else zero++;
                ++right;
                ++max1;
            }
            while (left < right && one > k && zero > k)
            {
                if (s[left] == '1') one--;
                else zero--;
                ++left;
                max1 += (right - left - 1);
            }
        }
        ++left;
        while (left < right)
        {
            max1 += (right - left);
            ++left;
        }
        return max1;
    }
};